package kata08;

import kata06.Trie;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class wordContainTwoWords03 {
    //容器
    private Trie tire;

    private Set<String> lengthLegalWords;

    //需要加入set的单词长度
    private int wordLength;

    private IWordCondition wordCondition;

    private wordContainTwoWords03() {}

    public wordContainTwoWords03(IWordCondition wordCondition, int wordLength) {
        this.tire = new Trie();
        lengthLegalWords = new HashSet<>();
        this.wordCondition = wordCondition;
        this.wordLength = wordLength;
    }

    //1.读文件
    public void WordsJoinTireByReadFile(String filePath){
        String file = this.getClass().getClassLoader().getResource(filePath).getFile();
        try(BufferedReader br = new BufferedReader(new FileReader(file))){
            String strLine;
            while ((strLine = br.readLine()) != null) {
                if(strLine.trim().length() == this.wordLength){
                    lengthLegalWords.add(strLine);
                }
                if (strLine.trim().length() < this.wordLength) {
                    tire.insert(strLine);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //2.获取字段数中符合要求的单词列表
    public List<String> getWordContainLegalWords(){
        return lengthLegalWords.stream().filter(str -> wordCondition.isContainTwoWords(str,tire)).collect(Collectors.toList());
    }


    //判断条件接口
    public interface IWordCondition {
        /**
         *  生成切分单词对象
         * @param word 源字符串
         * @return 单词对象
         */
        boolean isContainTwoWords(String word,Trie tire);
    }

    //接口实现类
    public static class WordContainTwoWord implements IWordCondition {

        @Override
        public boolean isContainTwoWords(String word,Trie tire) {
            int length = word.length();
            for(int i = 0; i < length; i++){
                if(tire.search(word.substring(0,(i+1))) && tire.search(word.substring((i+1),length))){
                    return true;
                }
            }
            return false;
        }
    }
}
